package com.wzz.demo.config;


import com.wzz.demo.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserServiceImpl userService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 指定账户和密码的来源
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }

    /**
     * 设置security认证的规则
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 指定登录表单的规则
        http.formLogin()
                // 这个路径必须和登录表单的提交路径一致
                .loginProcessingUrl("/login")
                // 设置自定义登录页面
                .loginPage("/login.html")
                // 设置登录成功后跳转页面
                .successForwardUrl("/main")
                .permitAll();

        // 没有权限时跳转的路径
        http.exceptionHandling().accessDeniedPage("/403.html");

        // 禁用跨站伪造请求, 不适用csrf过滤器
        http.csrf().disable();

        // 设置其他路径需要认证后才能访问
        http.authorizeRequests().anyRequest().authenticated();
    }
}
